# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="martin"
__date__ ="$16.01.2010 13:52:34$"
from PyQt4 import QtGui, QtCore
import sys
import subprocess
import scipy
import os



import fractal


class matrix_win(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.mat=QtGui.QImage(256, 256, QtGui.QImage.Format_Indexed8)
        
    def load(self, filename):
        self.mat=QtGui.QImage(filename)
        self.repaint()

    def paintEvent(self, ev):
        painter=QtGui.QPainter(self)
        painter.drawImage(QtCore.QPoint(0,0), self.mat)
        self.resize(self.mat.width(), self.mat.height() )

class gui_menue(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.mat_win=matrix_win()
        self.ifs_continous_run=0
        self.julia_continuos_run=0
        self.curlicue_continuos_run=0
        self.mat=scipy.zeros([200, 200])
        self.create_general_tab()
        self.create_ifs_tab()
        self.create_julia_tab()
        self.create_curlicue_tab()
        
        self.addTab(self.general_tab, "general")
        self.addTab(self.ifs_tab, "ifs")
        self.addTab(self.julia_tab, "julia")
        self.addTab(self.curlicue_tab, "curlicue")

    def create_general_tab(self):
        self.general_tab=QtGui.QWidget()
        vbox=QtGui.QVBoxLayout(self)
        xlabel=QtGui.QLabel("x-resolution")
        vbox.addWidget(xlabel)
        self.x_resolution=QtGui.QLineEdit("400")
        vbox.addWidget(self.x_resolution)
        ylabel=QtGui.QLabel("y-resolution")
        vbox.addWidget(ylabel)
        self.y_resolution=QtGui.QLineEdit("400")
        vbox.addWidget(self.y_resolution)

        showbutton=QtGui.QPushButton("show matrix")
        vbox.addWidget(showbutton)
        self.connect(showbutton,  QtCore.SIGNAL('clicked()'), self.
		show_matrix)
        savebutton=QtGui.QPushButton("save matrix")
        vbox.addWidget(savebutton)
        self.connect(savebutton,  QtCore.SIGNAL('clicked()'), self.
		save_matrix)
        quitbutton=QtGui.QPushButton("quit")
        vbox.addWidget(quitbutton)
        self.connect(quitbutton,  QtCore.SIGNAL('clicked()'), self,
		QtCore.SLOT('close()') )
        self.general_tab.setLayout(vbox)

    def create_ifs_tab(self):
        self.ifs_tab=QtGui.QWidget()
        self.ifs_vbox=QtGui.QVBoxLayout(self)
        self.ifs_filename=""
        self.transformation_filename=""
        self.ifs_filedialog_button=QtGui.QPushButton("ifs file")
        self.ifs_vbox.addWidget(self.ifs_filedialog_button)
        self.connect(self.ifs_filedialog_button,  QtCore.SIGNAL('clicked()'), self.
		get_ifs_filename)
        self.ifs_label=QtGui.QLabel(self.ifs_filename)
        self.ifs_vbox.addWidget(self.ifs_label)
        self.ifs_transformation_filedialog_button=QtGui.QPushButton("transformation function file")

        self.ifs_vbox.addWidget(self.ifs_transformation_filedialog_button)
        self.connect(self.ifs_transformation_filedialog_button,  QtCore.SIGNAL('clicked()'), self.
		get_transformation_filename)
        self.ifs_transformation_label=QtGui.QLabel(self.transformation_filename)
        self.ifs_vbox.addWidget(self.ifs_transformation_label)
        gamma_label=QtGui.QLabel("gamma-factor:")
        self.ifs_vbox.addWidget(gamma_label)
        self.ifs_gamma_factor=QtGui.QLineEdit("1.2")
        self.ifs_vbox.addWidget(self.ifs_gamma_factor)
        max_iterations_label=QtGui.QLabel("max. iterations")
        self.ifs_vbox.addWidget(max_iterations_label)
        self.max_ifs_iterations=QtGui.QLineEdit("100000")
        self.ifs_vbox.addWidget(self.max_ifs_iterations)
        self.ifs_runbutton=QtGui.QPushButton("run ifs")
        self.ifs_vbox.addWidget(self.ifs_runbutton)
        self.connect(self.ifs_runbutton,  QtCore.SIGNAL('clicked()'), self.
		run_ifs)
        self.ifs_random_runbutton=QtGui.QPushButton("random run")
        self.ifs_vbox.addWidget(self.ifs_random_runbutton)
        self.connect(self.ifs_random_runbutton,  QtCore.SIGNAL('clicked()'), self.
		random_run_ifs)
        self.ifs_ifs_continous_runbutton=QtGui.QPushButton("start continous run")
        self.ifs_vbox.addWidget(self.ifs_ifs_continous_runbutton)
        self.connect(self.ifs_ifs_continous_runbutton,  QtCore.SIGNAL('clicked()'), self.
		continous_run_ifs)
        self.ifs_tab.setLayout(self.ifs_vbox)

    def create_julia_tab(self):
        self.julia_tab=QtGui.QWidget()
        vbox=QtGui.QVBoxLayout(self)
        c_label_real=QtGui.QLabel("c real")
        vbox.addWidget(c_label_real)
        self.c_edit_real=QtGui.QLineEdit("1")
        vbox.addWidget(self.c_edit_real)
        c_label_imag=QtGui.QLabel("c imaginary")
        vbox.addWidget(c_label_imag)
        self.c_edit_imag=QtGui.QLineEdit("1")
        vbox.addWidget(self.c_edit_imag)
        max_iterations_label=QtGui.QLabel("max. iterations")
        vbox.addWidget(max_iterations_label)
        self.max_julia_iterations=QtGui.QLineEdit("100")
        vbox.addWidget(self.max_julia_iterations)
        runbutton=QtGui.QPushButton("run julia")
        vbox.addWidget(runbutton)
        random_run_button=QtGui.QPushButton("random run julia")
        vbox.addWidget(random_run_button)
        self.julia_continuos_runbutton=QtGui.QPushButton("start continous run")
        vbox.addWidget(self.julia_continuos_runbutton)
        self.connect(self.julia_continuos_runbutton,  QtCore.SIGNAL('clicked()'), self.
		continous_run_julia)
        self.connect(random_run_button,  QtCore.SIGNAL('clicked()'), self.
		random_run_julia)
        self.connect(runbutton,  QtCore.SIGNAL('clicked()'), self.
		run_julia_pic)
        self.julia_tab.setLayout(vbox)

    def create_curlicue_tab(self):
        self.curlicue_tab=QtGui.QWidget()
        vbox=QtGui.QVBoxLayout(self)
        s_value_label=QtGui.QLabel("s-value")
        vbox.addWidget(s_value_label)
        self.s_value_edit=QtGui.QLineEdit("(1+2**0.5)/2.0")
        vbox.addWidget(self.s_value_edit)
        max_iter_label=QtGui.QLabel("max. iterations")
        vbox.addWidget(max_iter_label)
        self.curlicue_max_iter=QtGui.QLineEdit("10**6")
        vbox.addWidget(self.curlicue_max_iter)
        gamma_label=QtGui.QLabel("gamma")
        vbox.addWidget(gamma_label)
        self.curlicue_gamma=QtGui.QLineEdit("1.2")
        vbox.addWidget(self.curlicue_gamma)
        runbutton=QtGui.QPushButton("run")
        vbox.addWidget(runbutton)
        random_run_button=QtGui.QPushButton("random run julia")
        vbox.addWidget(random_run_button)
        self.connect(runbutton,  QtCore.SIGNAL('clicked()'), self.
	run_curlicue_pic)
        self.connect(random_run_button,  QtCore.SIGNAL('clicked()'), self.
		random_run_curlicue)
        self.curlicue_continuos_runbutton=QtGui.QPushButton("start continous run")
        vbox.addWidget(self.curlicue_continuos_runbutton)
        self.connect(self.curlicue_continuos_runbutton,  QtCore.SIGNAL('clicked()'), self.
		continous_run_curlicue)
        self.curlicue_tab.setLayout(vbox)


    def show_matrix(self):
        
        scipy.misc.imsave("temp.png", self.mat)
        
        self.mat_win.load("temp.png")
        self.mat_win.show()




        
        #subprocess.Popen(["cmd.exe", "/C","temp.png"])
        
    def save_matrix(self):
        filename=QtGui.QFileDialog.getSaveFileName(self, "save file", "", "*.png")
        filename=str(filename)
        if filename!="":
            #print filename
            scipy.misc.imsave(filename, self.mat)

    def run_ifs(self):
        xwidth, ywidth=self.get_resolution()
        if xwidth >0 and ywidth > 0:
            iterations=self.get_ifs_iterations()
            if iterations >0:
                gamma_factor=self.get_ifs_gamma()
                if self.ifs_filename!="":
                    #p=Process(target=fractal.make_ifs_pic, args=[xwidth, ywidth, iterations, self.ifs_filename, self.transformation_filename])
                    #p.start()
                    #p.join()
                    
                    self.mat=fractal.make_ifs_pic(xwidth, ywidth, iterations, self.ifs_filename, self.transformation_filename, gamma_factor, self)
                    self.show_matrix()
                    #ifs=ifs_thread()
                    #ifs.render(xwidth, ywidth, iterations, self.ifs_filename, self.transformation_filename)
                    #self.mat=ifs.mat

    def continous_run_ifs(self):
        if self.ifs_continous_run==0:
            self.ifs_ifs_continous_runbutton.setText("stop continous run")
            self.ifs_continous_run=1
            self.random_run_ifs()
            
        else:
            self.ifs_ifs_continous_runbutton.setText("start continous run")
            self.ifs_continous_run=0

    def random_run_ifs(self):
        run=1

        while self.ifs_continous_run or run:
            run=0
            xwidth, ywidth=self.get_resolution()
            if xwidth >0 and ywidth > 0:
                iterations=self.get_ifs_iterations()
                if iterations >0:
                    gamma_factor=self.get_ifs_gamma()
                    tf_filename=self.get_random_filename(".tf")
                    ifs_filename=self.get_random_filename(".ifs")
                    print tf_filename, ifs_filename
                    self.mat=fractal.make_ifs_pic(xwidth, ywidth, iterations, ifs_filename, tf_filename, gamma_factor, self)
                    self.show_matrix()

    def get_random_filename(self, pattern):
        dir_list=os.listdir(".")
        filename_list=list([])
        for n in dir_list:
            if (pattern in n):
                filename_list.append(n)
        # print len(filename_list)
        i=scipy.random.randint(0, len(filename_list))
        return filename_list[i]

    def run_julia_pic(self):
        xwidth, ywidth=self.get_resolution()
        if xwidth >0 and ywidth > 0:
            c=self.get_c_value()
            #print c
            if c!="invalid":
                iterations=self.get_julia_iterations()
                if iterations >0:
                    
                    self.mat=fractal.make_julia_pic(xwidth, ywidth, c, iterations, self)
                    #self.progress.close()
                    self.show_matrix()
                    
    def random_run_julia(self):
        run=1
        while run or self.julia_continuos_run:
            run=0
            xwidth, ywidth=self.get_resolution()
            if xwidth >0 and ywidth > 0:
                c=complex(scipy.random.random(), scipy.random.random())
                print c
                if c!="invalid":
                    iterations=self.get_julia_iterations()
                    if iterations >0:

                        self.mat=fractal.make_julia_pic(xwidth, ywidth, c, iterations, self)
                        #self.progress.close()
                        self.show_matrix()

    def continous_run_julia(self):
        if self.julia_continuos_run==0:
            self.julia_continuos_runbutton.setText("stop continous run")
            self.julia_continuos_run=1
            self.random_run_julia()

        else:
            self.julia_continuos_runbutton.setText("start continous run")
            self.julia_continuos_run=0


    def run_curlicue_pic(self):
        xwidth, ywidth=self.get_resolution()
        if xwidth >0 and ywidth > 0:
            s=float(eval(str(self.s_value_edit.text())))
            #print c
            max_iter=float(eval(str(self.curlicue_max_iter.text())))
            gamma=float(eval(str(self.curlicue_gamma.text())))
            if type(s)==float:

                self.mat=fractal.make_curlicue_pic(xwidth, ywidth, s, gamma, max_iter, self)
                #self.progress.close()
                self.show_matrix()

    def random_run_curlicue(self):
        run=1
        while run or self.curlicue_continuos_run:
            run=0
            xwidth, ywidth=self.get_resolution()
            if xwidth >0 and ywidth > 0:
                s=scipy.random.random()
                #print c
                max_iter=float(eval(str(self.curlicue_max_iter.text())))
                gamma=float(eval(str(self.curlicue_gamma.text())))
                if type(s)==float:

                    self.mat=fractal.make_curlicue_pic(xwidth, ywidth, s, gamma, max_iter, self)
                    #self.progress.close()
                    self.show_matrix()

    def continous_run_curlicue(self):
        if self.curlicue_continuos_run==0:
            self.curlicue_continuos_runbutton.setText("stop continous run")
            self.curlicue_continuos_run=1
            self.random_run_curlicue()

        else:
            self.curlicue_continuos_runbutton.setText("start continous run")
            self.curlicue_continuos_run=0

    def get_c_value(self):
        c="invalid"
        try:
            c=complex(float(self.c_edit_real.text()), float(self.c_edit_imag.text()))
        except:
            self.error_msg("check c-value")
        return c

    def get_ifs_filename(self):
        self.ifs_filename=  QtGui.QFileDialog.getOpenFileName(self, "open file", "", "*.ifs");
        self.ifs_label.setText(self.ifs_filename)

    def get_transformation_filename(self):
        self.transformation_filename=  QtGui.QFileDialog.getOpenFileName(self, "open file", "", "*.tf");
        self.ifs_transformation_label.setText(self.transformation_filename)
        
    def get_resolution(self):
        xwidth=ywidth=0
        try:
            xwidth=int(self.x_resolution.text())
            ywidth=int(self.y_resolution.text())
        except:
            self.error_msg("check resolution")
        return xwidth, ywidth

    def get_julia_iterations(self):
        iterations=0
        try:
            iterations=int(self.max_julia_iterations.text())
        except:
            self.error_msg("check iterations")
        return iterations

    def get_ifs_iterations(self):
        iterations=0
        try:
            iterations=int(self.max_ifs_iterations.text())
        except:
            self.error_msg("check iterations")
        return iterations

    def get_ifs_gamma(self):
        gamma=0
        try:
            gamma=float(self.ifs_gamma_factor.text())
        except:
            self.error_msg("check gamma")
        return gamma
    
    def error_msg(self, text):
        msg=QtGui.QMessageBox()
        msg.setText(text)
        msg.exec_()

    def show_progress(self, i):
        self.progress.setValue(i)
        QtGui.QApplication.processEvents()

    def generate_progress_dialog(self, text, button_text, max):
        self.progress=QtGui.QProgressDialog(text, button_text, 0, max )

    def close_progress_dialog(self):
        self.progress.close()

    def closeEvent(self, ev):
        self.mat_win.close()


def main():
    app = QtGui.QApplication(sys.argv)
    gui=gui_menue()
    gui.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
    
